<!--对话框：切换组织机构-->
<template>
  <div>
    <a-modal
      :visible="visible"
      title="组织机构设置"
      :mask-closable="false"
      @before-ok="validate"
      @cancel="closeModal"
    >
      <a-tabs
        v-if="visible"
        v-model:activeKey="currentActiveTabKey"
        type="card-gutter"
      >
        <a-tab-pane key="1" title="切换组织机构">
          <div class="error-msg">{{ errorMessage }}</div>
          <a-form
            ref="currentOrgFormRef"
            :model="currentOrgForm"
            :label-col-props="{ span: 6 }"
            :wrapper-col-props="{ span: 18 }"
          >
            <a-form-item field="currentOrgId" label="当前组织机构">
              <a-select
                v-model="currentOrgForm.currentOrgId"
                :options="orgSelectOptions"
                :field-names="{
                  value: 'id',
                  label: 'orgName',
                }"
                :allow-search="true"
                :allow-clear="false"
                @change="changeCurrentOrgId"
              />
            </a-form-item>
            <a-form-item field="currentDeptId" label="当前部门">
              <a-select
                v-model="currentOrgForm.currentDeptId"
                :options="currentDeptSelectOptions"
                :field-names="{
                  value: 'id',
                  label: 'deptName',
                }"
                :allow-search="true"
                :allow-clear="false"
              />
            </a-form-item>
          </a-form>
        </a-tab-pane>
        <a-tab-pane key="2" title="设置主职组织机构/部门">
          <div class="error-msg">{{ errorMessage }}</div>
          <a-form
            ref="mainOrgFormRef"
            :model="mainOrgForm"
            :label-col-props="{ span: 6 }"
            :wrapper-col-props="{ span: 18 }"
          >
            <a-form-item field="mainOrgId" label="主职组织机构">
              <a-select
                v-model="mainOrgForm.mainOrgId"
                :options="orgSelectOptions"
                :field-names="{
                  value: 'id',
                  label: 'orgName',
                }"
                :allow-search="true"
                :allow-clear="false"
                @change="changeMainOrgId"
              />
            </a-form-item>
            <a-form-item field="mainDeptId" label="主职部门">
              <a-select
                v-model="mainOrgForm.mainDeptId"
                :options="mainDeptSelectOptions"
                :field-names="{
                  value: 'id',
                  label: 'deptName',
                }"
                :allow-search="true"
                :allow-clear="false"
              />
            </a-form-item>
          </a-form>
        </a-tab-pane>
      </a-tabs>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
  import { computed, ref } from 'vue';
  import { useTabBarStore, useUserStore } from '@/store';
  import { useRouter } from 'vue-router';
  import { DEFAULT_ROUTE_NAME } from '@/router/constants';
  import { setMainOrgDeptId } from '@/api/system/user';
  import { Notification } from '@arco-design/web-vue';
  import { switchOrgDept } from '@/api/system/online';

  defineProps({
    visible: { type: Boolean, default: false },
  });
  const emits = defineEmits(['update:visible']);

  const closeModal = () => {
    currentActiveTabKey.value = '1';
    initForm();
    errorMessage.value = '';
    emits('update:visible', false);
  };

  const errorMessage = ref('');
  const currentActiveTabKey = ref<string>('1'); // 当前选中的标签key
  const userStore = useUserStore();
  const router = useRouter();
  const tabBarStore = useTabBarStore();
  const changeOrgDept = async (done: (closed: boolean) => void) => {
    // 提交表单
    try {
      if (currentActiveTabKey.value === '1') {
        // 如果是在切换组织机构页签
        const formData = new FormData();
        formData.append('orgId', String(currentOrgForm.value.currentOrgId));
        formData.append('deptId', String(currentOrgForm.value.currentDeptId));
        const { data } = await switchOrgDept(formData);
        if (data === true) {
          Notification.success({
            content: '切换成功！',
            closable: true,
          });
          await userStore.info();
          tabBarStore.resetTabList();
          await router.push({ name: DEFAULT_ROUTE_NAME }); // 切换组织机构后跳到工作台
          closeModal();
          window.location.reload(); // 刷新页面
        }
      }
      if (currentActiveTabKey.value === '2') {
        // 如果是在设置主职组织机构页签点的提交
        const formData = new FormData();
        formData.append('orgId', String(mainOrgForm.value.mainOrgId));
        formData.append('deptId', String(mainOrgForm.value.mainDeptId));
        const { data } = await setMainOrgDeptId(formData);
        if (data === true) {
          Notification.success({
            content: '修改成功！',
            closable: true,
          });
          await userStore.info();
          tabBarStore.resetTabList();
          await router.push({ name: DEFAULT_ROUTE_NAME }); // 切换组织机构后跳到工作台
          closeModal();
        }
      }
    } catch (err) {
      initForm();
      errorMessage.value = (err as Error).message;
    } finally {
      done(true);
    }
  };
  const currentOrgFormRef = ref<any>();
  const mainOrgFormRef = ref<any>();
  const validate = async (done: (closed: boolean) => void) => {
    let errors;
    if (currentActiveTabKey.value === '1') {
      errors = await currentOrgFormRef.value.validate();
    } else {
      errors = await mainOrgFormRef.value.validate();
    }
    if (!errors) {
      changeOrgDept(done);
    }
  };
  const generateForm = () => {
    return {
      currentOrgId: userStore.currentOrgId, // 当前的组织机构id
      currentDeptId: userStore.currentDeptId, // 当前的部门id
      mainOrgId: userStore.mainOrgId, // 主职组织机构id
      mainDeptId: userStore.mainDept?.id, // 主职部门id
    };
  };
  const currentOrgForm = ref(generateForm());
  const mainOrgForm = ref(generateForm());
  const initForm = () => {
    currentOrgForm.value = {
      currentOrgId: userStore.currentOrgId, // 当前的组织机构id
      currentDeptId: userStore.currentDeptId, // 当前的部门id
      mainOrgId: userStore.mainOrgId, // 主职组织机构id
      mainDeptId: userStore.mainDept?.id, // 主职部门id
    };
    mainOrgForm.value = {
      currentOrgId: userStore.currentOrgId, // 当前的组织机构id
      currentDeptId: userStore.currentDeptId, // 当前的部门id
      mainOrgId: userStore.mainOrgId, // 主职组织机构id
      mainDeptId: userStore.mainDept?.id, // 主职部门id
    };
  };
  const orgSelectOptions = computed(() => {
    // 组织机构下拉选项
    const options = [] as any[];
    userStore.orgInfoList?.forEach((org) => {
      options.push({
        orgName: org.orgName,
        id: org.id,
      });
    });
    return options;
  });
  const mainDeptSelectOptions = computed(() => {
    // 主职组织机构对应的部门下拉选项
    let options = [] as any[];
    userStore.orgInfoList?.forEach((org) => {
      if (mainOrgForm.value.mainOrgId === org.id) {
        options = org.deptInfoList;
      }
    });
    return options;
  });
  const currentDeptSelectOptions = computed(() => {
    // 当前组织机构对应的部门下拉选项
    let options = [] as any[];
    userStore.orgInfoList?.forEach((org) => {
      if (currentOrgForm.value.currentOrgId === org.id) {
        options = org.deptInfoList;
      }
    });
    return options;
  });
  /**
   * @description 主职组织机构变化触发
   */
  const changeMainOrgId = (orgId: number) => {
    const oldMainOrgId = userStore.mainOrgId;
    if (orgId === oldMainOrgId) {
      mainOrgForm.value.mainDeptId = userStore.mainDept?.id;
    } else {
      mainOrgForm.value.mainDeptId = mainDeptSelectOptions.value[0].id;
    }
  };
  /**
   * @description 当前组织机构变化触发
   */
  const changeCurrentOrgId = (orgId: number) => {
    const oldCurrentOrgId = userStore.currentOrgId;
    if (orgId === oldCurrentOrgId) {
      currentOrgForm.value.currentDeptId = userStore.currentDeptId;
    } else {
      currentOrgForm.value.currentDeptId = currentDeptSelectOptions.value[0].id;
    }
  };
  initForm();
</script>

<style scoped lang="less">
  .error-msg {
    height: 32px;
    color: rgb(var(--red-6));
    line-height: 32px;
  }
</style>
